import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useMenuStore = defineStore('menu', () => {
  // 默认菜单顺序
  const defaultMenuOrder = [
    'flink-cluster',
    'jobs',
    'logs',
    'tools',
    'kafka-topic-monitor',
    'starrocks-tables',
    'starrocks-cluster-monitor',
    'alerts', 
    'savepoints',
    'jars',
    'third-party-config'
  ]

  // 当前菜单顺序（从localStorage加载或使用默认值）
  const menuOrder = ref(JSON.parse(localStorage.getItem('menuOrder')) || [...defaultMenuOrder])

  // 保存菜单顺序到localStorage
  const saveMenuOrder = (newOrder) => {
    menuOrder.value = newOrder
    localStorage.setItem('menuOrder', JSON.stringify(newOrder))
  }

  // 重置为默认顺序
  const resetMenuOrder = () => {
    menuOrder.value = [...defaultMenuOrder]
    localStorage.removeItem('menuOrder')
  }

  // 根据排序获取有序的菜单路由
  const getSortedMenuRoutes = (originalRoutes) => {
    if (!originalRoutes || originalRoutes.length === 0) {
      return []
    }

    // 创建路由映射
    const routeMap = {}
    originalRoutes.forEach(route => {
      routeMap[route.path] = route
    })

    // 按照menuOrder排序
    const sortedRoutes = []
    menuOrder.value.forEach(path => {
      if (routeMap[path]) {
        sortedRoutes.push(routeMap[path])
      }
    })

    // 添加不在排序列表中的新路由
    originalRoutes.forEach(route => {
      if (!menuOrder.value.includes(route.path)) {
        sortedRoutes.push(route)
      }
    })

    return sortedRoutes
  }

  return {
    menuOrder,
    defaultMenuOrder,
    saveMenuOrder,
    resetMenuOrder,
    getSortedMenuRoutes
  }
})
